package com.gzz.orchid.common.core.util.crypt;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 加密
 * https://blog.csdn.net/carol980206/article/details/96705859
 *
 * @author higmd
 */
@Slf4j
public class AESUtil {
    private static final String ALGORITHM = "AES";
    // AES/CBC/NOPaddin
    // AES 默认模式
    // 使用CBC模式, 在初始化Cipher对象时, 需要增加参数, 初始化向量IV : IvParameterSpec iv = new
    // IvParameterSpec(key.getBytes());
    // NOPadding: 使用NOPadding模式时, 原文长度必须是8byte的整数倍
    //"AES/ECB/PKCS5Padding"
    private static final String TRANSFORMATION = "AES/CBC/NOPadding";
    // 密钥种子（随机）
    private static final String SALT_KEY = "1234567812345678";
    // 密钥
    private static final SecretKeySpec SECRET_KEY;
    //向量
    private static final IvParameterSpec IV;


    static {
        // 生成密钥
        SECRET_KEY = new SecretKeySpec(SALT_KEY.getBytes(), ALGORITHM);
        // 创建初始化向量
        IV = new IvParameterSpec(SALT_KEY.getBytes());
    }

    /**
     * 加密
     *
     * @param original 需要加密的参数（注意必须是16位）
     */
    public static String encrypt(String original) {
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, SECRET_KEY, IV);
            return Base64.getEncoder().encodeToString(cipher.doFinal(original.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            log.error("Error while encrypting: " + e);
        }
        return null;
    }

    /**
     * 解码
     */
    public static String decrypt(String encrypted) {
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, SECRET_KEY, IV);
            return new String(cipher.doFinal(Base64.getDecoder().decode(encrypted)));
        } catch (Exception e) {
            log.error("Error while decrypting: " + e);
        }
        return null;
    }
}
